<template>
  <view class="order-detail-page">
    <!-- 订单状态 -->
    <view class="order-status-card">
      <view class="status-icon">
        <image :src="getStatusIcon(orderDetail.status)" class="icon" />
      </view>
      <view class="status-info">
        <text class="status-text">{{ getStatusText(orderDetail.status) }}</text>
        <text class="status-desc">{{ getStatusDesc(orderDetail.status) }}</text>
      </view>
    </view>

    <!-- 课程信息 -->
    <view class="course-card">
      <view class="card-title">课程信息</view>
      <view class="course-info">
        <image :src="orderDetail.courseInfo?.coverUrl" class="course-image" mode="aspectFill" />
        <view class="course-details">
          <text class="course-title">{{ orderDetail.courseInfo?.title }}</text>
          <text class="course-desc">{{ orderDetail.courseInfo?.description }}</text>
          <view class="course-meta">
            <text class="course-price">¥{{ orderDetail.courseInfo?.price }}</text>
            <text class="course-quantity">x{{ orderDetail.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-card">
      <view class="card-title">订单信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">订单编号</text>
          <text class="value">{{ orderDetail.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">下单时间</text>
          <text class="value">{{ formatTime(orderDetail.createTime) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.payTime">
          <text class="label">支付时间</text>
          <text class="value">{{ formatTime(orderDetail.payTime) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.confirmTime">
          <text class="label">确认时间</text>
          <text class="value">{{ formatTime(orderDetail.confirmTime) }}</text>
        </view>
        <view class="info-item">
          <text class="label">商家名称</text>
          <text class="value">{{ orderDetail.merchantName }}</text>
        </view>
      </view>
    </view>

    <!-- 价格明细 -->
    <view class="price-card">
      <view class="card-title">价格明细</view>
      <view class="price-list">
        <view class="price-item">
          <text class="label">课程价格</text>
          <text class="value">¥{{ orderDetail.courseInfo?.price }}</text>
        </view>
        <view class="price-item">
          <text class="label">数量</text>
          <text class="value">{{ orderDetail.quantity }}</text>
        </view>
        <view class="price-item" v-if="orderDetail.discountAmount > 0">
          <text class="label">优惠金额</text>
          <text class="value discount">-¥{{ orderDetail.discountAmount }}</text>
        </view>
        <view class="price-item total">
          <text class="label">实付金额</text>
          <text class="value">¥{{ orderDetail.totalAmount }}</text>
        </view>
      </view>
    </view>

    <!-- 联系信息 -->
    <view class="contact-card" v-if="orderDetail.contactInfo">
      <view class="card-title">联系信息</view>
      <view class="contact-info">
        <view class="contact-item">
          <text class="label">联系人</text>
          <text class="value">{{ orderDetail.contactInfo.name }}</text>
        </view>
        <view class="contact-item">
          <text class="label">联系电话</text>
          <text class="value">{{ orderDetail.contactInfo.phone }}</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button 
        v-if="orderDetail.status === 'pending'"
        class="action-btn cancel-btn"
        @click="cancelOrder"
      >
        取消订单
      </button>
      <button 
        v-if="orderDetail.status === 'pending'"
        class="action-btn pay-btn"
        @click="payOrder"
      >
        立即支付
      </button>
      <button 
        v-if="orderDetail.status === 'confirmed'"
        class="action-btn confirm-btn"
        @click="confirmOrder"
      >
        确认收货
      </button>
      <button 
        v-if="orderDetail.status === 'completed'"
        class="action-btn review-btn"
        @click="reviewOrder"
      >
        评价
      </button>
      <button 
        v-if="canRefund(orderDetail.status)"
        class="action-btn refund-btn"
        @click="refundOrder"
      >
        申请退款
      </button>
      <button 
        class="action-btn contact-btn"
        @click="contactMerchant"
      >
        联系商家
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Taro, { useRouter } from '@tarojs/taro'
import orderApi from '@/api/order'
import { formatTime, showLoading, hideLoading, showError, navigateTo } from '@/utils'

// 路由参数
const router = useRouter()
const { id } = router.params

// 响应式数据
const loading = ref(false)
const orderDetail = ref({})

// 页面加载
onMounted(() => {
  if (id) {
    loadOrderDetail()
  }
})

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    loading.value = true
    showLoading('加载中...')
    
    const result = await orderApi.getOrderDetail(id)
    
    if (result.code === 200) {
      orderDetail.value = result.data
    } else {
      showError(result.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    showError('加载失败，请重试')
  } finally {
    loading.value = false
    hideLoading()
  }
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    pending: '/static/images/status-pending.png',
    paid: '/static/images/status-paid.png',
    confirmed: '/static/images/status-confirmed.png',
    completed: '/static/images/status-completed.png',
    cancelled: '/static/images/status-cancelled.png',
    refunded: '/static/images/status-refunded.png'
  }
  return iconMap[status] || '/static/images/status-default.png'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态描述
const getStatusDesc = (status) => {
  const descMap = {
    pending: '请在30分钟内完成支付',
    paid: '商家正在确认您的订单',
    confirmed: '订单已确认，请等待服务',
    completed: '订单已完成，感谢您的使用',
    cancelled: '订单已取消',
    refunded: '订单已退款'
  }
  return descMap[status] || ''
}

// 判断是否可以退款
const canRefund = (status) => {
  return ['paid', 'confirmed'].includes(status)
}

// 取消订单
const cancelOrder = async () => {
  try {
    const res = await Taro.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？'
    })
    
    if (res.confirm) {
      showLoading('取消中...')
      await orderApi.cancelOrder(orderDetail.value.id, '用户主动取消')
      
      Taro.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      
      // 重新加载订单详情
      loadOrderDetail()
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    showError('取消失败，请重试')
  } finally {
    hideLoading()
  }
}

// 支付订单
const payOrder = async () => {
  try {
    showLoading('发起支付...')
    
    const result = await orderApi.wxPay(orderDetail.value.id)
    
    if (result.code === 200) {
      const paymentData = result.data
      
      // 调用微信支付
      await Taro.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType,
        paySign: paymentData.paySign
      })
      
      Taro.showToast({
        title: '支付成功',
        icon: 'success'
      })
      
      // 重新加载订单详情
      loadOrderDetail()
    }
  } catch (error) {
    console.error('支付失败:', error)
    if (error.errMsg && error.errMsg.includes('cancel')) {
      Taro.showToast({
        title: '支付已取消',
        icon: 'none'
      })
    } else {
      showError('支付失败，请重试')
    }
  } finally {
    hideLoading()
  }
}

// 确认收货
const confirmOrder = async () => {
  try {
    const res = await Taro.showModal({
      title: '确认收货',
      content: '确定已收到课程服务吗？'
    })
    
    if (res.confirm) {
      showLoading('确认中...')
      await orderApi.confirmOrder(orderDetail.value.id)
      
      Taro.showToast({
        title: '确认成功',
        icon: 'success'
      })
      
      // 重新加载订单详情
      loadOrderDetail()
    }
  } catch (error) {
    console.error('确认收货失败:', error)
    showError('确认失败，请重试')
  } finally {
    hideLoading()
  }
}

// 评价订单
const reviewOrder = () => {
  navigateTo('/pages/order/review', { orderId: orderDetail.value.id })
}

// 申请退款
const refundOrder = () => {
  navigateTo('/pages/order/refund', { orderId: orderDetail.value.id })
}

// 联系商家
const contactMerchant = () => {
  if (orderDetail.value.merchantPhone) {
    Taro.makePhoneCall({
      phoneNumber: orderDetail.value.merchantPhone
    })
  } else {
    showError('暂无商家联系方式')
  }
}
</script>

<style lang="less">
.order-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120px;
}

.order-status-card {
  background: white;
  padding: 40px 32px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;

  .status-icon {
    margin-right: 24px;

    .icon {
      width: 80px;
      height: 80px;
    }
  }

  .status-info {
    flex: 1;

    .status-text {
      font-size: 32px;
      font-weight: 600;
      color: #333;
      display: block;
      margin-bottom: 8px;
    }

    .status-desc {
      font-size: 24px;
      color: #666;
      display: block;
    }
  }
}

.course-card,
.order-info-card,
.price-card,
.contact-card {
  background: white;
  margin-bottom: 16px;
  padding: 32px;

  .card-title {
    font-size: 32px;
    font-weight: 600;
    color: #333;
    margin-bottom: 24px;
  }
}

.course-info {
  display: flex;

  .course-image {
    width: 160px;
    height: 120px;
    border-radius: 12px;
    flex-shrink: 0;
  }

  .course-details {
    flex: 1;
    margin-left: 24px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .course-title {
      font-size: 28px;
      font-weight: 500;
      color: #333;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .course-desc {
      font-size: 24px;
      color: #666;
      line-height: 1.4;
      margin-bottom: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .course-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .course-price {
        font-size: 32px;
        font-weight: 600;
        color: #F5A623;
      }

      .course-quantity {
        font-size: 24px;
        color: #999;
      }
    }
  }
}

.info-list,
.price-list {
  .info-item,
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28px;
      color: #666;
    }

    .value {
      font-size: 28px;
      color: #333;

      &.discount {
        color: #52C41A;
      }
    }

    &.total {
      border-top: 1px solid #f0f0f0;
      padding-top: 24px;
      margin-top: 8px;

      .label {
        font-weight: 600;
        color: #333;
      }

      .value {
        font-size: 32px;
        font-weight: 600;
        color: #F5A623;
      }
    }
  }
}

.contact-info {
  .contact-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28px;
      color: #666;
    }

    .value {
      font-size: 28px;
      color: #333;
    }
  }
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24px 32px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 16px;

  .action-btn {
    flex: 1;
    border: 1px solid #e0e0e0;
    border-radius: 24px;
    padding: 24px 16px;
    font-size: 28px;
    background: white;

    &.cancel-btn {
      color: #666;
    }

    &.pay-btn {
      background: #3478F6;
      color: white;
      border-color: #3478F6;
    }

    &.confirm-btn {
      background: #52C41A;
      color: white;
      border-color: #52C41A;
    }

    &.review-btn {
      color: #3478F6;
      border-color: #3478F6;
    }

    &.refund-btn {
      color: #FF4D4F;
      border-color: #FF4D4F;
    }

    &.contact-btn {
      color: #666;
      border-color: #e0e0e0;
    }
  }
}
</style>